﻿using System;
using System.Data;
using System.Configuration;
using System.Web.Security;
using Storage;
using Storage.EntityModels;
using Storage.Exceptions;

namespace Security
{
    public class SecuritySQLMembershipProvider : SqlMembershipProvider
    {
        private string connectionData = null;

        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            connectionData = config.Get("connectionStringName");
            base.Initialize(name, config);
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            MembershipUser newUser = base.CreateUser(username, password, email, passwordQuestion, passwordAnswer, 
                isApproved, providerUserKey, out status);

            return newUser;
        }

        public override bool ValidateUser(string username, string password)
        {
            User user;
            try
            {
                user = StorageManager.Instance.GetUserByUserName(username);
            }
            catch (Exception)
            {
                return false;
            }

            if (user.BookedIn)
            {
                return base.ValidateUser(username, password);
            }
            
            return false;
        }

        /// <summary>
        /// calculate the total number of users that are not unregistered and the number of online users
        /// </summary>
        /// <returns>return the number of these users</returns>
        public static int GetTotalUsers()
        {
            int tot_count = 0; //number of user active and that not have been unregistered
            MembershipUserCollection muc = Membership.GetAllUsers();
            foreach (MembershipUser u in muc)
            {
                try
                {
                    if (StorageManager.Instance.GetUserByUserName(u.UserName).BookedIn)
                    {
                        tot_count++;
                    }
                }
                catch (Storage.Exceptions.UserNotFoundException) 
                {
                    /*
                     * This happens when a user has been created in the membership provider 
                     * but not in the "profile" databases. Users like these are only "users 
                     * for testing phases" and they are not counted.
                     */
                }
            }
            return tot_count;
        }
    }
}

